package com.example.demo.demos.exportUtils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.example.demo.demos.exportUtils.interfaceUtils.Writable;
import org.apache.poi.ss.usermodel.Workbook;

import java.util.Map;
import java.util.function.Function;

/**
 * @Author xlj
 * @Date Created in  2024/3/15 17:13
 * @DESCRIPTION:
 * @Version V1.0
 */

public class ExcelTemplateExporter extends AbsExporter{
   private TemplateExportParams templateExportParams;

   private Function<Workbook, Workbook> afterRender;

   public ExcelTemplateExporter(String templateFilename) {
      this(templateFilename, null);
   }

   public ExcelTemplateExporter(String templateFilename, Function<Workbook, Workbook> afterRender) {
      this.templateExportParams = new TemplateExportParams("file/excelTemp/" + templateFilename + ".xlsx");
      this.afterRender = afterRender;
   }

   @Override
   public Writable render(Map<String, Object> dataSource) {
      Workbook workbook = ExcelExportUtil.exportExcel(this.templateExportParams, dataSource);
      if (null == workbook) {
         throw new NullPointerException("workbook 为 null");
      }
      if (this.afterRender != null) {
         workbook = this.afterRender.apply(workbook);
      }
      return new WorkbookWrapper(workbook);
   }

   @Override
   public String getTargetFileSuffix() {
      return ".xlsx";
   }

}
